/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mappedbytebuffer_demo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;


//I used the following namespace only for writing the final result into a text file
import java.io.*;
import java.nio.MappedByteBuffer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author teva
 */
public class MappedByteBuffer_Demo 
{

    private static long start=0;
    private static long end=0;
    static long Totaltime=0;
    private static String Filepath;
    private static boolean Blocking = true; 
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {  
        int k=0;
        int l=0;
        writeResult("================================");
        writeResult("MappedByteBuffer");
        writeResult("Configuration Blocking =>" + Blocking);
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
        Date date = new Date();
        writeResult("Test Date  " + dateFormat.format(date));
        writeResult("Included: [Prefetching.]");
        writeResult("================================");
        
        
        for(int i=11;i<12;i++) //To crawl 10 files
        {

          StringBuilder FP = new StringBuilder("/Users/teva/Desktop/DataFile/File").append(i).append(".txt"); 
                   
          Filepath = FP.toString();
          
          Prefecthing(Filepath);
                    
          StringBuilder FileName = new StringBuilder("File").append(i).append(".txt");
               
              for(k=1;k<2;k++) //this loop is used to change the buffer size
                 {
                    for(l=1;l<4;l++)
                     {
                       
                        writeResult("Iteration No=> " + l + " AND File name is=> " + FileName.toString() + "Total time =>" + SendFile(Filepath));
                        
                     }                
                 } 
            }  
    }
    
     public static void Prefecthing(String FilePath) throws FileNotFoundException, IOException 
    {
        
        FileChannel fc1 = null;
        
        fc1 = new FileInputStream(FilePath).getChannel();
        
        ByteBuffer bb = ByteBuffer.allocateDirect(100600);
        
        int len=0;
        
        while((len=fc1.read(bb))>=0) 
        {
            bb.clear();
        }
       
    }
    
    
     
    public static long SendFile(String FilePath)
    {
     SocketChannel sc = null;   
     try
      {
            System.out.println("Client NIO initiating...");            
            sc = SocketChannel.open();            
            boolean connected = sc.connect(new InetSocketAddress("10.141.11.125",3289)); 
            
            if(!connected)
            {
                connected = sc.finishConnect();
            }
            
            if(!connected)
            {
                throw(new IOException("Client failed to connect"));
            }
            
            System.out.println("Client channel connected");  
            
            sc.configureBlocking(Blocking); 
            
            RandomAccessFile memoryMappedFile = new RandomAccessFile(FilePath, "rw");
            
            MappedByteBuffer out = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, memoryMappedFile.getChannel().size());
            
            start = System.currentTimeMillis();
            
            while(out.hasRemaining())
            {
               
               sc.write(out); 
            }
          
           end = System.currentTimeMillis();
           
           Totaltime = end - start;
        
          sc.close();
          
          memoryMappedFile.getChannel().close();
            
          return Totaltime;
      }
      catch (IOException e) 
      {
            return -1;
      }     
    }
   
     
    public static void writeResult(String Results)
    {
        try 
        {
            FileWriter outFile = new FileWriter("/Users/teva/Desktop/FinalResult/MappedByteBufferResult.txt",true);
            PrintWriter out = new PrintWriter(outFile);
            out.println(Results);        
            out.close();
        } 
        catch(IOException e){}
     }
     

}
